<template>
  <div class="page">
    <!-- 页面头部 -->
    <el-page-header @back="goBack" content="创建维修工单">
      <template #icon>
        <el-icon><Tools /></el-icon>
      </template>
      <template #extra>
        <el-button type="primary" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </template>
    </el-page-header>

    <!-- 内容卡片 -->
    <el-card class="content-card">
      <el-form
        ref="formRef"
        :model="repairForm"
        :rules="formRules"
        label-width="100px"
        class="repair-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="工单标题" prop="title" required>
              <el-input
                v-model="repairForm.title"
                placeholder="请输入工单标题"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约时间" prop="reserveTime" required>
              <el-date-picker
                v-model="repairForm.reserveTime"
                type="datetime"
                placeholder="请选择预约时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="楼栋" prop="buildingId" required>
              <el-select
                v-model="repairForm.buildingId"
                placeholder="请选择楼栋"
                style="width: 100%"
                @change="onBuildingChange"
              >
                <el-option
                  v-for="building in buildings"
                  :key="building.id"
                  :label="building.name"
                  :value="building.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomId" required>
              <el-select
                v-model="repairForm.roomId"
                placeholder="请选择房间"
                style="width: 100%"
                :disabled="!repairForm.buildingId"
              >
                <el-option
                  v-for="room in availableRooms"
                  :key="room.id"
                  :label="room.roomNumber"
                  :value="room.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="维修类型" prop="type" required>
              <el-select
                v-model="repairForm.type"
                placeholder="请选择维修类型"
                style="width: 100%"
              >
                <el-option label="水电维修" :value="0" />
                <el-option label="家具维修" :value="1" />
                <el-option label="网络维修" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指定维修人员">
              <el-select
                v-model="repairForm.maintainerId"
                placeholder="自动分配"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="maintainer in maintainers"
                  :key="maintainer.id"
                  :label="`${maintainer.name} - ${maintainer.specialty}`"
                  :value="maintainer.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="des" required>
          <el-input
            v-model="repairForm.des"
            type="textarea"
            :rows="4"
            placeholder="请详细描述需要维修的问题..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
            v-model="repairForm.phone"
            placeholder="请输入联系电话"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitRepairOrder">
              <el-icon><Edit /></el-icon>
              提交工单
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Tools, ArrowLeft, Edit } from '@element-plus/icons-vue'
import { addOrderAPI } from '@/apis/orderAPI'
import { queryRoomAPI } from '@/apis/roomAPI'
import { queryDormBuild } from '@/apis/roomBuildAPI'
import { queryMaintainerAPI } from '@/apis/maintainerAPI'

const router = useRouter()
const formRef = ref()

// 表单数据
const repairForm = ref({
  title: '',
  reserveTime: '',
  buildingId: '',
  roomId: '',
  type: '',
  maintainerId: '',
  des: '',
  phone: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入工单标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  reserveTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  buildingId: [
    { required: true, message: '请选择楼栋', trigger: 'change' }
  ],
  roomId: [
    { required: true, message: '请选择房间', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择维修类型', trigger: 'change' }
  ],
  des: [
    { required: true, message: '请输入问题描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const buildings = ref([])
const rooms = ref([])
const maintainers = ref([])

const availableRooms = computed(() => {
  if (!repairForm.value.buildingId) return rooms.value
  return rooms.value.filter(room => String(room.buildingId) === String(repairForm.value.buildingId))
})

// 方法
const onBuildingChange = () => {
  repairForm.value.roomId = ''
}

const resetForm = () => {
  formRef.value?.resetFields()
}

const submitRepairOrder = async () => {
  try {
    // 验证表单
    await formRef.value?.validate()
    // 实际提交工单到后端
    await addOrderAPI(repairForm.value)
    ElMessage.success('维修工单提交成功！')
    resetForm()
    // 跳转到工单列表页面
    router.push('/repair/list')
  } catch (error) {
    ElMessage.error(error?.message || '请检查表单信息')
  }
}

const goBack = () => {
  router.go(-1)
}

onMounted(async () => {
  // 加载所有楼栋
  const bRes = await queryDormBuild()
  buildings.value = bRes.data || []
  // 加载所有房间
  const rRes = await queryRoomAPI({ pageNum: 1, pageSize: 999 })
  rooms.value = rRes.data?.records || rRes.data || []
  // 维修人员
  const mRes = await queryMaintainerAPI()
  maintainers.value = mRes.data || []
})
</script>

<style scoped>
.page {
  padding: 20px;
}

.content-card {
  margin-top: 20px;
}

.repair-form {
  padding: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}
</style>

